package server.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Hashtable;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import client.StreamCloser;
import com.google.gson.Gson;

import DAO.MessageDAO;
import DAO.TotalDao;
import model.*;
import server.main.server_main;

public class UpdateInformer {
	private int useraccount;
	private DataInputStream input;
	private DataOutputStream output;
	private StreamCloser s;
	private static final Logger logger = Logger.getLogger(UpdateInformer.class.getName());
	
	public UpdateInformer(int useraccount,Socket socket) {
		this.useraccount = useraccount;
        // 设置日志级别
        logger.setLevel(Level.INFO);
        // 创建一个文件处理器
        try {
        	String path = "." + File.separator + "log" + File.separator + "updateInformer.log";
            FileHandler fileHandler = new FileHandler(path);
            fileHandler.setLevel(Level.INFO);

            // 创建一个日志格式化器
            Formatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);

            // 将处理器添加到日志记录器
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
		try {
			input = new DataInputStream(socket.getInputStream());
			output = new DataOutputStream(socket.getOutputStream());
			Message mes = new Message();
			Gson gson = new Gson();
			
			//向申请进行UPDATE_FRIENDLIST的客户端返回连接成功
			mes.setType(MsgType.UPDATER_CONNECTED);
			String json = gson.toJson(mes);
			output.writeUTF(json);
			
			//向新登录用户的好友发送更新好友列表的提示
			this.capsulateMessage(useraccount);
																
		}catch (IOException e) {
			s.closeall(input,output);
			e.printStackTrace();
		}		
	}
	
	public void inform(Message mes) {
		Gson gson = new Gson();
		String json = gson.toJson(mes);		
		try {
			output.writeUTF(json);
		}catch (IOException e) {
			s.closeall(input,output);
			e.printStackTrace();
		}
	}
	
	//通知所有好友，要更新好友在线信息
	public void capsulateMessage(int user_account) {
		Message informMes = new Message();
		Gson gson = new Gson();
		TotalDao totaldao = new TotalDao(server_main.db.con);
		
		Hashtable<Integer, String> friends = totaldao.userFriends(user_account);         //好友列表
		Hashtable<Integer,UpdateInformer> updateinformers = UpdateInformManager.getallUpdateInformer();
		
		//判断好友当前的在线状态			
		for(Integer i : friends.keySet()) { 
			for(Integer j : server_main.onlineUsers) {
				//识别到了在线好友
				if(i.equals(j)) {
					int friend_id = totaldao.getUserId(i);	
					Hashtable<Integer, String> friend_friends = totaldao.userFriends(i);   //当前好友的所有好友
					Hashtable<Integer, String> friend_rooms = totaldao.userRooms(friend_id);           //当前好友的所有群聊
					Hashtable<Integer, Boolean> friend_states  = new Hashtable<Integer, Boolean>();   //当前好友的所有好友在线状态
					
					//在线好友的在线好友判别
					for(Integer m : friend_friends.keySet()) {
						friend_states.put(m, false);         //一开始的在线状态都设置成false
						for(Integer n : server_main.onlineUsers) {
							if(m.equals(n))
							{
								friend_states.put(m, true);
								break;
							}
						}  
					}
					
					String rjson = gson.toJson(friend_rooms);
					String sjson = gson.toJson(friend_states);
					String fjson = gson.toJson(friend_friends);
					informMes.setType(MsgType.UPDATE_FRIENDLIST);
					informMes.setText(fjson);
					informMes.setStates(sjson);
					informMes.setRooms(rjson);
					
					updateinformers.get(i).inform(informMes);
					System.out.println("发送成功");
					logger.info("发送成功");
				}
			}
		}
	}
	
	//用以通知对应的用户，有新的好友申请
	public void sendAddMessage(int recv_account) {
		Message mes = new Message();
		MessageDAO messageDAO = new MessageDAO(server_main.db.con);
		Gson gson = new Gson();
		
		Hashtable<Integer, String> messages = messageDAO.getAddMessages(recv_account);
		String mjson = gson.toJson(messages);
		
		mes.setType(MsgType.ADD_MESSAGE);
		mes.setText(mjson);
		this.inform(mes);
		
	}
	
	//提醒自己要更新好友列表了
	public void selfNotify(int myaccount) {
		Message informMes = new Message();
		Gson gson = new Gson();
		TotalDao totaldao = new TotalDao(server_main.db.con);
		Hashtable<Integer,UpdateInformer> updateinformers = UpdateInformManager.getallUpdateInformer();
		
		int user_id = totaldao.getUserId(myaccount);
		Hashtable<Integer, String> friends = totaldao.userFriends(myaccount);
		Hashtable<Integer, String> rooms = totaldao.userRooms(user_id);
		Hashtable<Integer, Boolean> states  = new Hashtable<Integer, Boolean>();
		
		for(Integer m : friends.keySet()) {
			states.put(m, false);         //一开始的在线状态都设置成false
			for(Integer n : server_main.onlineUsers) {
				if(m.equals(n))
				{
					states.put(m, true);
					break;
				}
			}  
		}
		
		String rjson = gson.toJson(rooms);
		String sjson = gson.toJson(states);
		String fjson = gson.toJson(friends);
		informMes.setType(MsgType.UPDATE_FRIENDLIST);
		informMes.setText(fjson);
		informMes.setStates(sjson);
		informMes.setRooms(rjson);
		
		updateinformers.get(myaccount).inform(informMes);
	}
}